// base
import Taro, { Component, navigateBack } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTEDIT } from './store/actions/pageselfmessage'
import { UPDATEPAGESELFMESSAGE } from './store/types/pageselfmessage'
import { UPDATEPAGEJOBVIEW } from '../job-view/store/types/pagejobview'
import { UPDATEPAGECHOOSEJOBINPUT } from '../../pages/choose-job-input/store/types/pagechoosejobinput'

// less
import './index.less'

import NetworkError from '../../components/taro-ui/network-error'
import { showLoading, hideLoading, showToast } from '../../crossplatform/apiservice/toast'
import { formatDate } from '../../util/lodashmin/formatDate'
import ChooseGender from '../../components/page-components/choose-gender'
import MessageSelectWrap from './components/message-select-wrap'
import { deepCopy } from '../../util/lodashmin'
import MessageInputWrap from '../../components/page-components/message-input-wrap'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import { getZhichuUserInfo, upDateUserInfo } from '../../store/actions/userinfo'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import BtmFixedBtn from '../../components/page-components/btm-fixed-btn'
import pagejumplist from '../../configuration/pagejumplist.json'
import MessageSelectSingle from '../../components/page-components/message-select-single'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGESELFMESSAGE,
      payload: {
        ...payload
      }
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  updateJobView(payload) {
    dispatch({
      type: UPDATEPAGEJOBVIEW,
      payload: {
        ...payload
      }
    })
  },
  getZhichuUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  dosubmit(payload) {
    if (!this.timer) {
      this.timer = null
    }
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      showLoading({
        title: '玩命加载中'
      })
    }, 2000)
    return new Promise(resolve => {
      let promise = upDateUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        clearTimeout(this.timer)
        this.timer = null
        hideLoading()
        resolve(data)
      })
    })
  },
  doedit(payload) {
    return new Promise(resolve => {
      DOREQUESTEDIT(payload).then(({ status, message }) => {
        if (status) {
          let timer = setTimeout(() => {
            clearTimeout(timer)
            navigateBack()
          }, 500)
          resolve()
        } else {
          resolve()
          showToast({
            title: message || '保存失败'
          })
        }
      })
    })
  },
  updateJobInput(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ pageselfmessage, pagechoosejobinput, userinfo }) => ({
    ...pageselfmessage,
    zhichuUserId: userinfo.zhichuUserId,
    mobile: userinfo.mobile,
    userId: userinfo.userId,
    openId: userinfo.openId,
    userInfoC: userinfo.userInfoC,
    role: userinfo.role,
    jobinput: pagechoosejobinput.inputData
  }),
  mapActiontoProps
)
class SelfMessage extends Component {
  config = {
    navigationBarTitleText: '基本信息'
  }

  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false
    }
  }

  componentWillMount() {
    // onLoad
    const { userId, mobile: mobilein } = this.props
    this.props.updateState({
      submitdata: {
        name: '',
        sex: '1',
        birthday: new Date().getFullYear() - 18,
        phone: ''
      },
      selectdatalist: [
        {
          mode: 'date',
          name: '出生年份',
          start: '1900-01-01',
          end: formatDate('', 'YYYY-MM-DD'),
          type: 'birthday',
          fields: 'year',
          value: ''
        },
        {
          name: '手机号',
          type: 'phone',
          value: ''
        }
      ],
      cant: false
    })
    if (userId) {
      this.props.getZhichuUserInfo({ userId }).then(data => {
        const { selectdatalist } = this.props
        const { userInfoC, mobile } = data
        let selectdatalistNew = [...selectdatalist]
        let submitdata = {
          name: userInfoC.userName,
          sex: userInfoC.gender,
          birthday: userInfoC.gmtBirth,
          phone: mobile || mobilein
        }
        selectdatalistNew[0].value = userInfoC.gmtBirth
        selectdatalistNew[1].value = mobile
        this.props.updateState({
          submitdata,
          selectdatalist: selectdatalistNew
        })
      })
    }
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    this.setMobile()
    this.doOnShowInput && this.doOnShowInput()
    this.doOnShowInput = null

    this.props.updateState({
      modalPhoneVisible: false
    })
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  setMobile = () => {
    const { mobile, selectdatalist, submitdata } = this.props
    if (mobile) {
      const selectdatalistNew = [...selectdatalist]
      let submitdataNew = { ...submitdata }
      selectdatalistNew[1].value = mobile
      submitdataNew.phone = mobile
      this.props.updateState({
        selectdatalist: selectdatalistNew,
        submitdata: submitdataNew
      })
    }
  }

  doOnShowInput = null
  onInputChange = ({ type, value, name, componenttype, maxLength, tip }) => {
    this.doOnShowInput = () => {
      let submitdata = deepCopy(this.props.submitdata)
      submitdata.name = this.props.jobinput.value
      this.props.updateState({
        submitdata
      })
    }
    this.props.updateJobInput({
      inputData: { type, value, name, componenttype, maxLength, tip }
    })
    navigateTo({
      url: `${pagejumplist['choose-job-input'].path}`
    })
  }
  onSelectChange = ({ type, value }) => {
    const dataSource = deepCopy(this.props.selectdatalist)
    const { submitdata } = this.props
    let subdata = {}
    subdata[type] = value

    let returndata = []
    dataSource.forEach(data => {
      if (data.type == type) {
        data.value = value
      }
      returndata.push(data)
    })
    this.props.updateState({
      selectdatalist: dataSource,
      submitdata: {
        ...submitdata,
        ...subdata
      }
    })
  }

  getSubmitData = () => {
    const { userId, selectdatalist, zhichuUserId, role } = this.props
    let year = new Date().getFullYear() - 18
    let { submitdata } = this.props
    submitdata.birthday = submitdata.birthday || year
    const phone = selectdatalist[1].value
    if (!phone) {
      showToast({
        title: '请填写手机号'
      })
      return
    }
    if (!submitdata.name) {
      showToast({
        title: '请填写姓名'
      })
      return
    }
    const currentyear = new Date().getFullYear()
    if (submitdata.birthday > currentyear) {
      showToast({
        title: '出身年份不能大于当前'
      })
      return
    }
    if (zhichuUserId) {
      const result = this.formatDataToSubmit({
        ...submitdata,
        userId,
        phone,
        settype: 'edit',
        zhichuUserId
      })
      this.props
        .doedit({
          ...result
        })
        .then(() => {
          this.props.getZhichuUserInfo({ userId })
        })
    } else {
      const result = this.formatDataToSubmit({ ...submitdata, userId, phone })
      this.props.dosubmit({ ...result }).then(() => {
        this.props.getZhichuUserInfo({ userId })
      })
    }
  }

  formatDataToSubmit({ settype, birthday, name, phone, sex, userId, role, zhichuUserId }) {
    const { userAvator } = this.props.userInfoC
    let result = {}
    if (settype == 'edit') {
      result.id = zhichuUserId
    } else {
      result.userId = userId
    }
    if (settype == 'edit') {
      result.gmtBirth = birthday + (birthday.length === 4 ? '-01-01 00:00:00' : '')
    } else {
      result.birth = birthday + (birthday.length === 4 ? '-01-01 00:00:00' : '')
    }
    result.mobile = phone
    result.sex = sex
    result.role = role
    result.userAvator = userAvator || ''
    result.userName = name
    return result
  }

  showGenderModal = () => {
    // 编辑性别
    this.setState({
      modalVisible: true
    })
  }

  onCancel = () => {
    // 隐藏弹框
    this.setState({
      modalVisible: false
    })
  }

  onClickGender = gender => {
    // 选中性别
    const { submitdata } = this.props
    this.props.updateState({
      submitdata: {
        ...submitdata,
        sex: gender
      }
    })
  }

  render() {
    const { networkerror, selectdatalist, submitdata } = this.props
    const { modalVisible } = this.state
    return (
      <View className="SelfMessage_id20868">
        <NetworkError visible={networkerror} />
        <View className={`SelfMessage_id20868Wrap ${networkerror ? 'hide' : ''}`}>
          <View className="top-title">
            <View className="title">
              <View className="title-text">基本信息</View>
              {/* <View className="title-btn" onClick={this.getSubmitData}>
                保存
              </View> */}
            </View>
            <View className="desc">*完善个人信息能更快的找到心仪的工作</View>
          </View>
          <View className="top-container">
            <MessageInputWrap
              maxLength="6"
              name="姓名"
              value={submitdata.name}
              tip="*请填写真实姓名"
              onChange={this.onInputChange}
            />
            <MessageSelectSingle
              name="性别"
              type="gender"
              value={submitdata.sex === 'female' ? '女' : '男'}
              onChange={this.showGenderModal}
            />
            <MessageSelectWrap dataSource={[selectdatalist[0]]} onChange={this.onSelectChange} />
          </View>

          <View className="bottom-container">
            <MessageSelectWrap dataSource={[selectdatalist[1]]} onChange={this.onSelectChange} />
          </View>

          <BtmFixedBtn text="保存" onTap={this.getSubmitData} />
        </View>

        <AtActionSheet isOpened={modalVisible} onClose={this.onCancel}>
          <ChooseGender title="选择性别" value={submitdata.sex} onChange={this.onClickGender} />
        </AtActionSheet>
      </View>
    )
  }
}

export default SelfMessage
